<!-- 自查-卡片页（公共） -->
<template>
  <view class="page-all">
    <Header :title="title" bgColor="#fff" :leftIconSize="20"/>
    <Tabs :list="tabsList" @changeTab="changeTab"/>
    <!-- 搜索 -->
    <view class="search-content">
      <view class="left">
        <uv-search :placeholder="searchTitle" bgColor="#fff" v-model="queryForm.schoolName" :showAction="false" @change="searchFun()" @clear="clearFun()"/>
      </view>
      <view class="screen-icon" @click="showScreen">
        <image v-if="iconFlag === true" src="@/static/image/index/icon2.png" mode="widthFix"/>
        <image v-else src="@/static/image/index/icon1.png" mode="widthFix"/>
      </view>
    </view>
    <!-- 卡片内容 -->
    <view class="list-container">
      <scroll-view scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered" :lower-threshold="50"
                   :style="{height: `calc(100vh - 44px - 66px - ${TopHeight.top}px)`}" @scrolltolower="nextPage" :refresher-threshold="80"
                   refresher-background="rgb(244, 244, 244)" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                   @refresherrestore="onRestore" @refresherabort="onAbort">
        <view v-if="dataList.length > 0" class="indic-swipe">
          <view class="item" v-for="(item, index) in dataList" :key="index" @click="viewFun(item.id)">
              <view class="img">
                <image :src="item.filePath"/>
                <view class="statu" :class="{ green: selectTabValue === '40' }">
                  <span v-if="selectTabValue === '20'">{{ item.rectifyStatus === '10' ? '待整改' : '待审核' }}</span>
                  <span v-else>已完成</span>
                </view>
              </view>
              <view class="info">
                <!-- 主内容 -->
                <view>
                  <view class="row">
                    <view class="title">{{ item.entryType === '5' ? '配餐单位名称:' : '学校名称:' }}</view>
                    <view class="con">{{ item.schoolName }}</view>
                  </view>
                  <view class="row">
                    <view class="title">指标名称:</view>
                    <view class="con">{{ item.targetName }}</view>
                  </view>
                  <view class="row">
                    <view class="title">检查日期:</view>
                    <view class="con">{{ item.lawDate }}</view>
                  </view>
                  <view class="row sign">
                    <view class="title" style="width: 150rpx">检查人签名:</view>
                    <view class="con">
                      <image :src="item.caterSign" mode="heightFix"/>
                    </view>
                  </view>
                </view>
                <!-- 按钮 -->
                <view class="btn-row" v-if="selectTabValue === '20' && item.rectifyStatus !== '10'">
                  <button @click="auditFun(item.id)">审核</button>
                </view>
                <view v-if="selectTabValue === '40'" class="btn-row" >
                  <button @click="getInspectionReport(item)">检查报告</button>
                  <button v-if="item.rectifyStatus === '20'" @click="getRectificationReport(item)">整改报告</button>
                </view>
              </view>
          </view>
          <uni-load-more :status="loadingType" :content-text="contentText"/>
        </view>
        <view v-if="emptyFlag" class="empty-box">
          <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"/>
        </view>
      </scroll-view>
    </view>
    <!-- 筛选弹层 -->
    <uv-popup ref="popup" @change="change" :closeable="true">
      <view class="popup-title">筛选</view>
      <view class="popup-content">
        <view class="popup-title-row" v-if="queryForm.lawStatus !== '40'">
          <text>状态</text>
        </view>
        <view class="popup-con-row" v-if="queryForm.lawStatus !== '40'">
          <view v-for="(item, index) in rectifyStatusList" :key="index" class="item"
                :class="{actived:item.id === rectifyStatus}" @click="rectifyStatusFun(item)">
            {{ item.name }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>检查日期</text>
        </view>
        <view class="popup-date-row">
          <view class="date" @click="showCalendar()">{{ lawStartDate }}</view>
          <view class="to">至</view>
          <view class="date" @click="showCalendar()">{{ lawEndDate }}</view>
          <uv-calendars ref="calendar" reset-text="清空" @reset="dateReset" mode="range" @confirm="dateConfirm" allowSameDay="true"/>
        </view>
        <view class="popup-title-row" v-if="queryForm.entryType !== '5'">
          <text>办学性质</text>
        </view>
        <view class="popup-con-row" v-if="queryForm.entryType !== '5'">
          <view v-for="(item, index) in schoolNatureList" :key="index" class="item"
                :class="{actived:item.value === schoolNature}" @click="schoolNatureFun(item)">
            {{ item.name }}
          </view>
        </view>
        <view class="popup-title-row" v-if="queryForm.entryType !== '5'">
          <text>办学类型</text>
        </view>
        <view class="popup-con-row" v-if="queryForm.entryType !== '5'">
          <view v-for="(item,index) in schoolTypeList" :key="index" class="item"
                :class="{actived:item.value === schoolType}" @click="schoolTypeFun(item)">
            {{ item.name }}
          </view>
        </view>
        <view class="popup-title-row"  v-if="areaList.length>0">
          <text>地区</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item,index) in areaList" :key="index" class="item"
                :class="{actived:item.code === area}" @click="areaFun(item)">
            {{ item.name }}
          </view>
        </view>
        <view class="bottom-box" @click.stop>
          <button class="yellow-sure-button" style="width: 49%" @click.stop="resetForm()">重置</button>
          <button class="sure-button" @click.stop="popupSubmit()">确认</button>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
  import lawAPI from '@/api/law/supLaw/supLaw';
  import publicAPI from '@/api/law/public/public';
  import dictAPI from "@/api/dict/dict";
  import {onLoad} from '@dcloudio/uni-app';
  import {ref, reactive, getCurrentInstance, defineProps} from 'vue';
  import supLawApi from "@/api/law/supLaw/supLaw";
  import TopHeight from "@/common/topHeight"
  import dayjs from "dayjs";
  import config from "@/common/config";
  let imgMinioPath = ref(config.IMG_MINIO_PATH);
  const {proxy} = getCurrentInstance();
  const props = defineProps({
    entryType: {
      type: String,
      default: ''
    },
  });
  let iconFlag = ref(false);
  const freshing = ref(false);
  const triggered = ref(false);
  const emptyFlag = ref(false);
  const loadingType = ref('noMore');
  const contentText = reactive({
    contentdown: "上拉显示更多",
    contentrefresh: "正在加载...",
    contentnomore: "没有更多数据了"
  });

  let internalFlag = ref(false);
  let title = ref("");
  let searchTitle = ref("");
  const selectTabValue = ref('20');
  const tabsList = ref([
    {
      id: '20',
      name: '待审核'
    },
    {
      id: '40',
      name: '已完成'
    }
  ]);
  const total = ref(0);
  let dataList = ref([]);
  let data = ref({});
  let userInfo = ref(uni.getStorageSync('userInfo'));
  const queryForm = reactive({ // 查询条件
    pageSize: 10,
    pageNum: 1,
    entryType: '',
    createOrgId: userInfo.value.user.orgId,
    lawStatus: '20', // 检查状态 待上传检查记录单：10, 待审核:20,待复查:30,已复查:40'
    rectifyStatus: '', // 整改状态 待整改: 10 , 已整改: 20
    schoolName: '', // 学校or配餐单位名称
    canteenName: '', // 食堂名称
    lawDetail: {
      schoolPropertiesCode: '', // 办学性质
      doSchoolTypeCode: '', // 办学类型
      countyId: '', // 地区
    },
    params: {
      lawStartDate: '',
      lawEndDate: ''
    }
  });

  /** 数据加载 */
  onLoad(async () => {
    queryForm.entryType = props.entryType;
    uni.setStorageSync('entryType', queryForm.entryType);
    if (queryForm.entryType === '4') {
      title.value = '学校隐患自查';
      searchTitle.value = '学校名称';
      queryForm.sourceType = '02';
      getSchoolNatureList();
      getSchoolTypeList();
    } else if (queryForm.entryType === '3') {
      title.value = '食堂隐患自查';
      searchTitle.value = '学校名称';
      queryForm.sourceType = '02';
      getSchoolNatureList();
      getSchoolTypeList();
    } else if (queryForm.entryType === '8') {
      title.value = '学校有害生物自查';
      searchTitle.value = '学校名称';
      queryForm.sourceType = '02';
      getSchoolNatureList();
      getSchoolTypeList();
    } else {
      title.value = '配餐单位隐患自查';
      searchTitle.value = '配餐单位名称';
      queryForm.sourceType = '03';
    }
    getAreaList();
    searchFun();
  });

  /** tab页切换 */
  function changeTab(e) {
    dataList.value = [];
    selectTabValue.value = e.id;
    queryForm.lawStatus = e.id;
    resetForm();
  }

  /** 搜索 */
  let searchFun = () => {
    queryForm.pageNum = 1;
    getListData();
  };

  /** 清空搜索 */
  let clearFun = () => {
    searchFun();
  }

  /** 获取数据列表 */
  let getListData = async () => {
    let res = await proxy.http.asyncPost(lawAPI.getsupLawPage, queryForm);
    if (res.code === 0) {
      total.value = res.data.total;
      if (queryForm.pageNum === 1) {
        dataList.value.length = 0;
      }
      let tmp = queryForm.pageNum === 1 ? res.data.records : dataList.value.concat(res.data.records);
      dataList.value = tmp;
      if (dataList.value.length < total.value) {
        loadingType.value = 'more';
      } else {
        loadingType.value = 'noMore'; //没有数据时显示‘没有更多’
      }
      emptyFlag.value = dataList.value.length <= 0;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 查看 */
  function  viewFun(id) {
    if (!internalFlag.value) {
      uni.navigateTo({
        url: '/packageSelfInspection/pages/viewInfo/viewDetail?id=' + id
      });
    }
    internalFlag.value = false;
  }

  /** 审核 */
  function auditFun(id) {
    internalFlag.value = true;
    uni.navigateTo({
      url: '/packageSelfInspection/pages/audit/index?id=' + id,
      success: () => {
        uni.$once("refresh", () => {
          searchFun();
        });
      }
    });
  }

  /** 检查报告 */
  function getInspectionReport(item) {
    internalFlag.value = true;
    uni.showLoading({title: '下载中', mask: true});
    let header = proxy.http.handleHeader('HEADER_JSON', '', false)
    uni.downloadFile({ //只能是GET请求
      url: supLawApi.downloadLawPdfById(item.id),//下载地址接口返回
      header: header,
      success: (res) => {
        //下载成功
        if (res.statusCode === 200) {
          //保存文件
          let tempFile = res.tempFilePath;
          //文件名称
          let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
          //保存成功之后 打开文件
          uni.getFileSystemManager().saveFile({
            tempFilePath: tempFile,
            filePath: wx.env.USER_DATA_PATH + '/' + fileName + '检查报告.pdf',//自定义文件名
            success(red) {
              uni.showModal({
                title: '提示',
                content: '文件已保存：' + red.savedFilePath,
                cancelText: '我知道了',
                confirmText: '打开文件',
                success: function (res) {
                  if (res.confirm) {
                    uni.openDocument({
                      filePath: red.savedFilePath,
                      showMenu: true,
                      success: (sus) => {
                        // 添加分享
                        uni.onShareAppMessage(function () {});
                      }
                    })
                  }
                }
              });
            }
          })
        }
        uni.hideLoading();
      },
      fail: (e) => {
        console.log(e, '文件下载失败')
        uni.showToast({
          title: '文件下载失败',
          icon: "error",
        })
        uni.hideLoading();
      }
    });
  }

  /** 整改报告 */
  function getRectificationReport(item) {
    internalFlag.value = true;
    uni.showLoading({title: '下载中', mask: true});
    let header = proxy.http.handleHeader('HEADER_JSON', '', false)
    uni.downloadFile({ //只能是GET请求
      url: supLawApi.downloadLawRectifyPdfById(item.id),//下载地址接口返回
      header: header,
      success: (res) => {
        //下载成功
        if (res.statusCode === 200) {
          //保存文件
          let tempFile = res.tempFilePath;
          //文件名称
          let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
          //保存成功之后 打开文件
          uni.getFileSystemManager().saveFile({
            tempFilePath: tempFile,
            filePath: wx.env.USER_DATA_PATH + '/' + fileName + '整改报告.pdf',//自定义文件名
            success(red) {
              uni.showModal({
                title: '提示',
                content: '文件已保存：' + red.savedFilePath,
                cancelText: '我知道了',
                confirmText: '打开文件',
                success: function (res) {
                  if (res.confirm) {
                    uni.openDocument({
                      filePath: red.savedFilePath,
                      showMenu: true,
                      success: (sus) => {
                        // 添加分享
                        uni.onShareAppMessage(function () {});
                      }
                    })
                  }
                }
              });
            }
          })
        }
        uni.hideLoading();
      },
      fail: (e) => {
        console.log(e, '文件下载失败')
        uni.showToast({
          title: '文件下载失败',
          icon: "error",
        })
        uni.hideLoading();
      }
    });
  }
  let changeIcon = () => {
    if (queryForm.params.lawStartDate || queryForm.params.lawEndDate ||
       queryForm.checkStatus || queryForm.rectifyStatus || queryForm.lawDetail.countyId || queryForm.lawDetail.cityId ||
        queryForm.lawDetail.schoolPropertiesCode || queryForm.lawDetail.doSchoolTypeCode ) {
      iconFlag.value = true;
    } else {
      iconFlag.value = false;
    }
  }
  /** 筛选下拉 */
  let popup = ref();
  // 显示-筛选
  function showScreen() {
    popup.value.open('bottom');
  }
  // 取消-筛选
  const close = () => {

  };
  // 确认-筛选
  function popupSubmit() {
    queryForm.rectifyStatus = rectifyStatus.value;
    queryForm.checkStatus = '';
    if (queryForm.rectifyStatus === '20'){
      queryForm.checkStatus = '10';
      queryForm.rectifyStatus = '';
    }
    if (lawStartDate.value !== '开始日期') {
      queryForm.params.lawStartDate = lawStartDate.value;
    }
    if (lawEndDate.value !== '结束日期') {
      queryForm.params.lawEndDate = lawEndDate.value;
    }
    queryForm.lawDetail.schoolPropertiesCode = schoolNature.value;
    queryForm.lawDetail.doSchoolTypeCode = schoolType.value;
    if (areaType.value === '1') {
      queryForm.lawDetail.cityId = area.value;
    } else {
      queryForm.lawDetail.countyId = area.value;
    }
    changeIcon();
    popup.value.close();
    searchFun();
  }
  // 重置-筛选
  function resetForm() {
    rectifyStatus.value = '';
    schoolNature.value = '';
    schoolType.value = '';
    lawStartDate.value = '开始日期';
    lawEndDate.value = '结束日期'
    area.value = '';
    queryForm.params.lawStartDate = '';
    queryForm.params.lawEndDate = '';
    queryForm.lawDetail.schoolPropertiesCode = '';
    queryForm.lawDetail.doSchoolTypeCode = '';
    queryForm.rectifyStatus = '';
    queryForm.checkStatus = '';
    queryForm.lawDetail.countyId = '';
    queryForm.lawDetail.cityId = '';
    iconFlag.value = false;
    popup.value.close();
    searchFun();
  }
  function dateReset(){
    lawStartDate.value = '开始日期';
    lawEndDate.value = '结束日期'
  }
  /** 筛选-状态 */
  const rectifyStatus = ref('');
  const rectifyStatusList = ref([
    {id: '20', name: '待审核'},
    {id: '10', name: '待整改'}
  ]);
  // 筛选选中
  const rectifyStatusFun = (item) => {
    if (rectifyStatus.value === item.id) {
      rectifyStatus.value = '';
    } else {
      rectifyStatus.value = item.id;
    }
  };

  /** 筛选-检查日期 */
  const lawStartDate = ref('开始日期');
  const lawEndDate = ref('结束日期');
  const calendar = ref();
  // 弹出开始时间选择
  function showCalendar() {
    calendar.value.open();
  }
  // 弹出开始时间选择
  function dateConfirm(e) {
    lawStartDate.value = e.range.before;
    lawEndDate.value = e.range.after;
  }

  /** 筛选-办学性质 */
  const schoolNature = ref('');
  const schoolNatureList = ref([]);
  // 获取办学性质列表
  let getSchoolNatureList = async () => {
    let res = await proxy.http.asyncGet(dictAPI.findDataListByType('school_properties'), {});
    if (res.code === 0) {
      schoolNatureList.value = res.data;
    }
  };
  // 筛选选中
  const schoolNatureFun = (item) => {
    if (schoolNature.value === item.value) {
      schoolNature.value = '';
    } else {
      schoolNature.value = item.value;
    }
  };

  /** 筛选-办学类型 */
  const schoolType = ref('');
  const schoolTypeList = ref([]);
  // 获取办学类型列表
  let getSchoolTypeList = async () => {
    let res = await proxy.http.asyncGet(dictAPI.findDataListByType('do_school_type'), {});
    if (res.code === 0) {
      schoolTypeList.value = res.data;
    }
  };
  // 筛选选中
  const schoolTypeFun = (item) => {
    if (schoolType.value === item.value) {
      schoolType.value = ''
    } else {
      schoolType.value = item.value;
    }
  };

  /** 筛选-地区 */
  const area = ref('');
  const areaList = ref([]);
  let areaType = ref('');
  // 获取地区列表
  let getAreaList = async () => {
    let query = {};
    if (userInfo.value.user.org.county) { // 区
      areaType.value = '3';
      return;
    } else if (userInfo.value.user.org.city) { // 市
      areaType.value = '2';
      query.parentCode = userInfo.value.user.org.city;
    } else { // 省
      areaType.value = '1';
      query.parentCode = userInfo.value.user.org.province;
    }
    let res = await proxy.http.asyncPost(publicAPI.getAreaListByParentCode(query.parentCode));
    if (res.code === 0) {
      areaList.value = reactive(res.data);
    }
  };
  // 筛选选中
  const areaFun = (item) => {
    if (area.value === item.code) {
      area.value = ''
    } else {
      area.value = item.code;
    }
  };

  /** 滚动视图区域 */
  // 翻页
  let nextPage = () => {
      console.log(queryForm.pageNum * queryForm.pageSize)
      console.log(total.value)
    if (queryForm.pageNum * queryForm.pageSize < total.value) {
      queryForm.pageNum++;
      getListData()
    }
  }
  // 下拉
  let onPulling = () => {
    freshing.value = false;
    setTimeout(() => {
      triggered.value = true;
    }, 1000)
  };
  // 刷新
  let onRefresh = () => {
    if (freshing.value) return;
    triggered.value = 'restore';
    setTimeout(() => {
      freshing.value = false;
      triggered.value = false;
    }, 1000)
    //获取数据的函数
    queryForm.pageNum = 1 // 记录数
    getListData()
  };
  let onRestore = () => {
    triggered.value = 'restore'; // 需要重置
  };
  let onAbort = () => {
    console.log("onAbort");
  };
</script>

<style lang="scss" scoped>
  .bottom-box {
    padding: 0;

    .sure-button {
      width: 49% !important;
    }
  }
  .list-container{
    .item{
      padding: 20rpx!important;
    }
  }
  .popup-con-row{
    .item{
      display: flex!important;
      align-items: center!important; /* 垂直居中 */
      justify-content: center!important; /* 水平居中，可选 */
    }
  }
  .btn-row{
    margin-top: 30rpx!important;
    position: unset!important;
    padding-right:20rpx!important;
  }
</style>
